package com.zbkj.service.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.constants.WeChatConstants;
import com.zbkj.common.model.user.UserToken;
import com.zbkj.service.dao.user.UserTokenDao;
import com.zbkj.service.thirdparty.login.enums.LoginTypeEnum;
import com.zbkj.service.service.user.UserTokenService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户token表-service接口-实现类
 * @author lijie
 */
@Service
public class UserTokenServiceImpl extends ServiceImpl<UserTokenDao, UserToken> implements UserTokenService {

    @Resource
    private UserTokenDao dao;

    /**
     * 检测token是否存在
     * @param token String openId
     * @param type int 类型
     * @return UserToken
     */
    @Override
    public UserToken getByOpenidAndType(String token, int type) {
        LambdaQueryWrapper<UserToken> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserToken::getType, type).eq(UserToken::getToken, token);
        return dao.selectOne(lambdaQueryWrapper);
    }

    /**
     * 绑定token关系
     * @param token String token
     * @param type int 类型
     * @author Mr.Zhang
     * @since 2020-05-25
     */
    @Override
    public void bind(String token, int type, Integer userId) {
        UserToken userToken = new UserToken();
        userToken.setToken(token);
        userToken.setType(type);
        userToken.setUid(userId);
        save(userToken);
    }

    @Override
    public UserToken getTokenByUserId(Integer userId, int type) {
        LambdaQueryWrapper<UserToken> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserToken::getUid, userId).eq(UserToken::getType, type);
        return dao.selectOne(lambdaQueryWrapper);
    }

    @Override
    public int getTokenType(String typeStr) {
        switch (typeStr) {
            case WeChatConstants.USER_TYPE_PUBLIC: return Constants.THIRD_LOGIN_TOKEN_TYPE_PUBLIC;
            case WeChatConstants.USER_TYPE_PROGRAM: return Constants.THIRD_LOGIN_TOKEN_TYPE_PROGRAM;
            case Constants.USER_LOGIN_TYPE_PHONE: return Constants.THIRD_LOGIN_TOKEN_TYPE_PHONE;
            default: return 0;
        }
    }

    @Override
    public void saveOrUpdate(int uid, LoginTypeEnum loginTypeEnum, String token) {
        //保存或更新token
        UserToken userToken =  this.getTokenByUserId(uid, loginTypeEnum.getLoginTokenType());
        if(userToken == null){
            userToken = new UserToken();
            userToken.setToken(token);
            userToken.setUid(uid);
            userToken.setType(loginTypeEnum.getLoginTokenType());
            this.save(userToken);
        }else{
            userToken.setToken(token);
            this.updateById(userToken);
        }
    }
}

